﻿using System;
using System.Web.Mvc;
using System.Web;
using System.Web.Security;
using System.Web.Caching;
using System.Net.Mail;
using System.Collections.Specialized;
using Microsoft.Health.Web;
using Microsoft.Health;
using Microsoft.Health.ItemTypes;
using System.Collections.Generic;
using FusionAPI;

public class PFSyncController : Controller
{
    public ContentResult GetGraphHeights(PFSync.User u)
    {
        List<GraphItemValue> heights = (List<GraphItemValue>)Session["heights"];
        if (heights == null)
        {
            heights = new List<GraphItemValue>();

            HealthRecordItemCollection heightItems = GetItems(u, Height.TypeId);
            foreach (Height h in heightItems)
            {
                heights.Add(new GraphItemValue(h.When.ToDateTime(), h.Value.Value));
            }
            Session["heights"] = heights;
        }

        return Content(GetJSONFromGraphValues("Height", heights), "application/json");
    }

    public ContentResult GetGraphWeights(PFSync.User u)
    {
        List<GraphItemValue> weights = (List<GraphItemValue>)Session["weights"];
        if(weights == null)
        {
            weights = new List<GraphItemValue>();

            HealthRecordItemCollection weightItems = GetItems(u, Weight.TypeId);
            foreach (Weight w in weightItems)
                weights.Add(new GraphItemValue(w.When.ToDateTime(), w.Value.Value));

            Session["weights"] = weights;
        }
        return Content(GetJSONFromGraphValues("Weight", weights), "application/json");
    }

    public ContentResult GetGraphBPDiastolic(PFSync.User u)
    {
        
        List<GraphItemValue> bpDiastolic = (List<GraphItemValue>)Session["bpDiastolic"];

        if (bpDiastolic == null)
        {
            this.BloodPressureItems(u);
            bpDiastolic = (List<GraphItemValue>)Session["bpDiastolic"];
        }

        return Content(GetJSONFromGraphValues("Diastolic", bpDiastolic), "application/json");
    }

    public ContentResult GetGraphBPSystolic(PFSync.User u)
    {
        List<GraphItemValue> bpSystolic = (List<GraphItemValue>)Session["bpSystolic"];
        if (bpSystolic == null)
        {
            this.BloodPressureItems(u);
            bpSystolic = (List<GraphItemValue>)Session["bpSystolic"];
        }

        return Content(GetJSONFromGraphValues("Systolic", bpSystolic), "application/json");
    }

    public ContentResult GetGraphBPHeartRate(PFSync.User u)
    {
        List<GraphItemValue> bpHeartRate = (List<GraphItemValue>)Session["bpHeartRate"];
        if (bpHeartRate == null)
        {
            this.BloodPressureItems(u);
            bpHeartRate = (List<GraphItemValue>)Session["bpHeartRate"];
        }

        return Content(GetJSONFromGraphValues("Pulse", bpHeartRate), "application/json");
    }

    private void BloodPressureItems(PFSync.User u)
    {
        List<GraphItemValue> bpDiastolic = new List<GraphItemValue>();
        List<GraphItemValue> bpSystolic = new List<GraphItemValue>();
        List<GraphItemValue> bpHeartRate = new List<GraphItemValue>();

        HealthRecordItemCollection hrItems = GetItems(u, BloodPressure.TypeId);
        foreach (BloodPressure w in hrItems)
        {
            bpDiastolic.Add(new GraphItemValue(w.When.ToDateTime(), w.Diastolic));
            bpSystolic.Add(new GraphItemValue(w.When.ToDateTime(), w.Systolic));
            bpHeartRate.Add(new GraphItemValue(w.When.ToDateTime(), w.Pulse.Value));
        }

        Session["bpDiastolic"] = bpDiastolic;
        Session["bpSystolic"] = bpSystolic;
        Session["bpHeartRate"] = bpHeartRate;
    }

    private HealthRecordItemCollection GetItems(PFSync.User u, Guid itemType)
    {
        if (Session["User"] != null)
        {
            u = ((PFSync.User)Session["User"]);
        }
        Guid appID = new Guid(System.Configuration.ConfigurationSettings.AppSettings["ApplicationId"]);
        string healthServiceURL = System.Configuration.ConfigurationSettings.AppSettings["HealthServiceUrl"];
        OfflineWebApplicationConnection connection = new OfflineWebApplicationConnection(appID, healthServiceURL, new Guid(u.PersonIdHV));
        // Authenticate connection
        connection.Authenticate();
        HealthRecordAccessor accessor = new HealthRecordAccessor(connection, new Guid(u.RecordIdHV));
        HealthRecordItemCollection items = accessor.GetItemsByType(itemType);
        return items;
    }

    private string GetJSONFromGraphValues(List<GraphItemValue> values)
    {
        return GetJSONFromGraphValues(string.Empty, values);
    }

    private string GetJSONFromGraphValues(string label, List<GraphItemValue> values)
    {
        System.Text.StringBuilder json = new System.Text.StringBuilder();
        json.Append("{ label:\""+label+"\", data: [");

        foreach (GraphItemValue i in values)
            json.Append("[" + i.JSONDateTime + ", " + i.Value + "],");

        json = json.Remove(json.Length - 1, 1);

        if (label != "Diastolic" && label != "Pulse")
            json.Append("], color: '#337733'}");

        else if (label == "Pulse")
            json.Append("], color: '#A51717'}");

        else
            json.Append("], color: '#3377A7'}");

        return json.ToString();
    }

    public JsonResult GetSyncHistory(PFSync.User u)
    {
        if (Session["User"] != null)
            u = ((PFSync.User)Session["User"]);

        List<PFSync.Sync> syncHistory = PFSync.Sync.RestoreSyncListByIdUser(u.IdUser);                       

        return Json(syncHistory);
    }
    public JsonResult GetUser(PFSync.User u)
    {
        if (Session["User"] != null)
        {
            u = ((PFSync.User)Session["User"]);
        }
        return Json(u);
    }
    public JsonResult SyncHVandPF(PFSync.User u)
    {
        if (Session["User"] != null)
        {
            u = ((PFSync.User)Session["User"]);
        }

        CLinicalData FusionData = new CLinicalData();
        FusionData.Url = System.Configuration.ConfigurationManager.AppSettings["FusionAPI.ClinicalDataValue"];

        FusionAPI.Security pfSecurity = new Security();
        pfSecurity.Url = System.Configuration.ConfigurationManager.AppSettings["FusionAPI.Security"];
        LoginResult LoginResultClass = new LoginResult();
        OperationStatus1 OperatingStatusObject = new OperationStatus1();       
        LoginResultClass = pfSecurity.Login(System.Configuration.ConfigurationManager.AppSettings["FusionAPIUser"], System.Configuration.ConfigurationManager.AppSettings["FusionAPIPassword"], out OperatingStatusObject);
        string pfVendorAPIToken = LoginResultClass.token.ToString();

        Guid appID = new Guid(System.Configuration.ConfigurationSettings.AppSettings["ApplicationId"]);
        string healthServiceURL = System.Configuration.ConfigurationSettings.AppSettings["HealthServiceUrl"];
        OfflineWebApplicationConnection connection = new OfflineWebApplicationConnection(appID, healthServiceURL, new Guid(u.PersonIdHV));
        connection.Authenticate();

        if (PFSync.SyncManager.SyncAll(connection, new Guid(u.RecordIdHV), FusionData, pfVendorAPIToken, u.PatientIdPF))
        {
            return Json("<span style='color: #337733;'>Successfully synchronized PatientFusion and HealthVault!</span>");
        }
        else
        {
            return Json("<span style='color: #773333;'>Unsuccessful synchronization attempt!</span>");
        }
    }

	public void DefaultView()
	{
        Response.Redirect("/index.html");
	}
}

